//
//  DBManager.m
//  Browser
//
//  Created by eric on 10/27/14.
//  Copyright (c) 2014 eric. All rights reserved.
//

#import "DBManager.h"

static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
@implementation DBManager

+ (DBManager*) getSharedInstance
{
    if(!sharedInstance)
    {
        sharedInstance = [[super allocWithZone:NULL] init];
        [sharedInstance createDB];
    }
    return sharedInstance;
}

- (BOOL) createDB
{

    NSString *docsDir;
    NSArray *dirPaths;
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = ([dirPaths count] > 0) ? [dirPaths objectAtIndex:0] : nil;
    databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"browserDB.sqlite"]];
    NSLog(databasePath);
    BOOL isSuccess = YES;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if ([fileMgr fileExistsAtPath:databasePath] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS IMAGES (URL TEXT UNIQUE, IMAGE BLOB)";
            if(sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!= SQLITE_OK)
            {
                isSuccess = NO;
                NSLog(@"Failed to create table");
            }
            sqlite3_close(database);
            return isSuccess;
        }else
        {
            isSuccess = NO;
            NSLog(@"Failed to open/create database");
        }
    
    }
    return isSuccess;
}

- (BOOL) insertImage:(NSString *)mainUrl mainUrl: (NSData*)imgData
{
    const char *dbpath = [databasePath UTF8String];
    if(sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        //"INSERT INTO IMAGES (URL, IMAGE) VALUES (?, ?)";
        const char* insertSql = "INSERT INTO IMAGES (URL, IMAGE) VALUES (?, ?)";
        if(sqlite3_prepare_v2(database, insertSql, -1, &statement, NULL) == SQLITE_OK)
        {
            sqlite3_bind_text(statement, 1, [mainUrl UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_blob(statement, 2, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
           
           if(sqlite3_step(statement)==SQLITE_DONE)
           {
              sqlite3_finalize(statement);
              sqlite3_close(database);
              return YES;
           }else
           {
              NSLog(@"inesert failed");
              
           }
        }

    }else
    {
       NSLog(@"inesert failed");
    }
    return NO;

}

// Load images from data base with given image url
- (NSData*) loadAllImagesByUrl: (NSString*) imageLink
{
    NSData* data = nil;
    NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT IMAGE FROM IMAGES WHERE URL = '%@'", imageLink];
   const char *dbpath = [databasePath UTF8String];
   if(sqlite3_open(dbpath, &database) == SQLITE_OK)
   {
    if( sqlite3_prepare_v2(database, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
    {
        if( sqlite3_step(statement) == SQLITE_ROW )
        {
            int length = sqlite3_column_bytes(statement, 0);
            data = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
        }
    }
   }
    // Finalize and close database.
    sqlite3_finalize(statement);
    sqlite3_close(database);
    return data;
    
}


- (NSMutableArray*) loadAllImageURLs
{
    NSMutableArray *allRows = [[NSMutableArray alloc] init];
    NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT * FROM IMAGES"];
   const char *dbpath = [databasePath UTF8String];
   if(sqlite3_open(dbpath, &database) == SQLITE_OK)
   {
      if( sqlite3_prepare_v2(database, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
      {
         while (sqlite3_step(statement) == SQLITE_ROW)
         {
            char *fieldUrl = (char*)sqlite3_column_text(statement, 0);
            NSString *fieldUrlStr = [[NSString alloc] initWithUTF8String:fieldUrl];
//            int length = sqlite3_column_bytes(statement, 1);
//            NSData* data = [NSData dataWithBytes:sqlite3_column_blob(statement, 1) length:length];
            NSLog(@"Load %@",fieldUrlStr);
//            NSLog(@"Image Data %@", data);
            [allRows addObject:fieldUrlStr];
         }
      }
   }
   sqlite3_finalize(statement);
   sqlite3_close(database);
   
   return allRows;
}

- (NSMutableArray*) loadAllImagesFromSql
{
    NSMutableArray *allRows = [[NSMutableArray alloc] init];
    NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT * FROM IMAGES"];
//    sqlite3_stmt* statement;
   const char *dbpath = [databasePath UTF8String];
   if(sqlite3_open(dbpath, &database) == SQLITE_OK)
   {
      if( sqlite3_prepare_v2(database, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
      {
         while (sqlite3_step(statement) == SQLITE_ROW)
         {
            char *fieldUrl = (char*)sqlite3_column_text(statement, 0);
            NSString *fieldUrlStr = [[NSString alloc] initWithUTF8String:fieldUrl];
            int length = sqlite3_column_bytes(statement, 1);
            NSData* data = [NSData dataWithBytes:sqlite3_column_blob(statement, 1) length:length];
            NSLog(@"Load %@",fieldUrlStr);
            NSLog(@"Image Data %@", data);
            [allRows addObject:data];
         }
      }
      
     
   }
   sqlite3_finalize(statement);
   sqlite3_close(database);
   
    return allRows;
    
}


@end
